const categoryService = require('../../../services/categoryService');
const { successRes, errorRes } = require('../../../utils/responseHandler');

// 获取分类列表
const getList = async (req, res) => {
    try {
        const params = req.query;
        const categories = await categoryService.getAllCategoriesService(params);
        successRes(res, categories);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 获取单个分类详情
const getDetail = async (req, res) => {
    try {
        const categoryId = req.params.id;
        const category = await categoryService.getCategoryById(categoryId);
        successRes(res, category);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 创建或更新分类
const createOrUpdate = async (req, res) => {
    try {
        const categoryId = req.body.id;
        let category;
        if (categoryId) {
            // 更新分类
            category = await categoryService.updateCategory(categoryId, req.body);
        } else {
            // 创建新分类
            category = await categoryService.addCategory(req.body);
        }
        successRes(res, category);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 删除分类
const deleteCategory = async (req, res) => {
    try {
        const categoryId = req.params.id;
        await categoryService.deleteCategoryService(categoryId);
        successRes(res, { message: 'Category deleted successfully' });
    } catch (err) {
        errorRes(res, err.message);
    }
};

module.exports = {
    getList,
    getDetail,
    createOrUpdate,
    deleteCategory
};
